#include "sdl.h"

void pause();
int Affichage(SDL_Surface *ecran, SDL_Rect position, int **Grille, int size, SDL_Surface *rectangle, int w, int h);

void* Init(void* **Grillearg, void* taille){


    int **Grille = (int**) Grillearg;
    int size = (int) taille;
    SDL_Surface *ecran = NULL, *rectangle = NULL;
    SDL_Rect position;
    int w = 630/size, h=470/size,i,j,k,l;
 
    position.x = (640/2)-(WIDTH/2); //centrage
    position.y = (480/2)-(HEIGHT/2);
 
    SDL_Init(SDL_INIT_VIDEO);
 
    ecran = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
    rectangle = SDL_CreateRGBSurface(SDL_HWSURFACE, w, h, 32, 0, 0, 0, 0); 
    SDL_WM_SetCaption("test grille", NULL);
 
    SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 255, 0));   
    
    for(k=0,i=0;i<HEIGHT;i+=h+1,k++)
    {
        position.y = i;
	    SDL_FillRect(rectangle, NULL, SDL_MapRGB(ecran->format, 255, 255, 255)); 
	    SDL_BlitSurface(rectangle, NULL, ecran, &position);
        for(j=0,l=0;j<WIDTH;j+=w+1,l++)	
        {
	        position.x = j;
            SDL_FillRect(rectangle, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
            SDL_BlitSurface(rectangle, NULL, ecran, &position); 
        }
    }

    Affichage(ecran, position, Grille, size, rectangle, w, h);

    SDL_Flip(ecran);  
//    pause(); 
//    SDL_FreeSurface(rectangle);     
    return EXIT_SUCCESS;
}

int Affichage(SDL_Surface *ecran, SDL_Rect position, int** Grille, int size, SDL_Surface *rectangle, int w, int h)
{
    int i,j;
    for(i=0; i<=size-1; i++)
    {
        for(j=0; j<=size-1; j++)
        {
            position.y = i*h + i; //coord*h + coord(marge)
            position.x = j*w + j; //coord*w + coord(marge)
            if (Grille[i][j]==1)
            {

                SDL_FillRect(rectangle, NULL, SDL_MapRGB(ecran->format, 0, 0, 0));
                SDL_BlitSurface(rectangle, NULL, ecran, &position); 
            }
            else
                SDL_FillRect(rectangle, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
                SDL_BlitSurface(rectangle, NULL, ecran, &position); 
        }
    }
    return EXIT_SUCCESS;
}


void pause()
{
    int continuer = 1;
    SDL_Event event;
 
    while (continuer)
    {
        SDL_PollEvent(&event);
        switch(event.type)
        {
            case SDL_QUIT:
                continuer = 0;
                break;
            case SDL_MOUSEBUTTONUP:
                //event.button.x;
                break;
        }
    }
}
